<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue-swiper-组件</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/VUE/swiper/swiper-bundle.min.css">
    <script src="/VUE/swiper/swiper-bundle.min.js"></script>
    <script src="/VUE/vue2.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .swiper {
            width: 1400px;
            height: 355px;
            margin: 20px auto;
            box-sizing: border-box;
            overflow: hidden;
        }

        .swiper img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
<div id="box">
    <header>导航栏</header>

    <!-- 为了解决子组件swiper的mounted会初始化过早问题，需要给swiper加上:key="datalist.length"，当数据长度发生改变时，swiper因为key值不同会销毁重新创建，这是mounted也会重新执行一次 -->
    <!--  <swiper :key="datalist.length">  -->

    <!--  用v-if可以避免数据长度为0时也被创建  -->
    <swiper v-if="datalist.length" :key="datalist.length">
        <swiper-item v-for="item in datalist" :key="item">
            <img :src="item" alt="">
        </swiper-item>
    </swiper>

    <footer>底部内容</footer>
</div>
</body>
<script>
    Vue.component("swiperItem",{
        template: `
            <div class="swiper-slide">
                <slot></slot>
            </div>
        `
    })

    Vue.component("swiper", {
        template: `
        <div class="swiper">
            <div class="swiper-wrapper">
                <slot></slot>
            </div>
             <!-- 如果需要分页器 -->
            <div class="swiper-pagination"></div>
        </div>`,

        mounted() {
            console.log("mounted")
            // 初始化过早
            new Swiper(".swiper", {

                loop: true, // 循环模式选项

                // 如果需要分页器
                pagination: {
                    el: '.swiper-pagination',
                },

                //自动轮播
                autoplay: {
                    delay: 2500,
                    disableOnInteraction: false,
                },
            })
        },
        destroyed(){
            console.log("destroyed")
        }
    })

    let vm = new Vue({
        el: "#box",
        data:{
            datalist: [],
        },

        mounted() {
            setTimeout(() => {
                this.datalist = ["/images/01.jpg", "/images/02.jpg", "/images/04.jpg"]
            }, 2000)
        },
    })
</script>
</html>